<?php

namespace App\Console\Commands;

use App\Models\product\ProductSonModel;
use App\Models\system\ExceptionTableModel;
use App\Models\users\UsersModel;
use App\Service\product\ProductApiService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Redis;

class TaskCreateProductUsersQrcode extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'app:task-create-product-users-qrcode';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Execute the console command.
     */
    public function handle(): void
    {
        try {

            $uid = 0;
            $product_id = 0;
            if (Redis::exists('task-product-qrcode:uid')) {
                $uid = Redis::get('task-product-qrcode:uid');
            }
            if (Redis::exists('task-product-qrcode:product_id')) {
                $product_id = Redis::get('task-product-qrcode:product_id');
            }
            if (!$uid) {
                $userId = UsersModel::where('id', '>', $uid)->orderBy('id', 'asc')->value('id');
                Redis::setex('task-product-qrcode:uid', 3600, $userId);
            } else {

                $productId = ProductSonModel::where('id', '>', $product_id)->orderBy('id', 'asc')->value('id');
                if ($productId) {
                    ProductApiService::instance()->createProductQrcode($uid, $productId);
                    Redis::setex('task-product-qrcode:product_id', 3600, $productId);
                } else {
                    Redis::del('task-product-qrcode:product_id');
                    $uid = UsersModel::where('id', '>', $uid)->orderBy('id', 'asc')->value('id');
                    if (!$uid) {
                        Redis::del('task-product-qrcode:uid');
                    } else {
                        Redis::setex('task-product-qrcode:uid', 3600, $uid);
                    }
                }

            }

        } catch (\Exception $e) {
            ExceptionTableModel::insert([
                'type' => '创建产品二维码任务异常',
                'message' => $e->getMessage()  . $e->getFile() . $e->getLine(),
            ]);
        }
    }
}
